package cn.sinata.wanglin;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.easemob.redpacketsdk.RPCallback;
import com.easemob.redpacketsdk.RedPacket;
import com.easemob.redpacketui.RedPacketConstant;
import com.easemob.redpacketui.utils.RedPacketUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.util.NetUtils;
import com.qihoo.appstore.common.updatesdk.lib.UpdateHelper;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.fragment.utils.FragmentTabHost;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.PermissionManager;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.GroupDao;
import cn.sinata.wanglin.db.dao.GroupUserDao;
import cn.sinata.wanglin.db.dao.PushDao;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.mine.activity.LoginStyleActivity;
import cn.sinata.wanglin.mine.fragment.MineFragment;
import cn.sinata.wanglin.model.Group;
import cn.sinata.wanglin.model.WeatherInfo;
import cn.sinata.wanglin.neighbor.fragment.NeighborFragment;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.net.model.util.ResultSubscriber;
import cn.sinata.wanglin.property.fragment.PropertyFragment;
import cn.sinata.wanglin.publish.activity.PubhomeActivity;
import cn.sinata.wanglin.publish.fragment.PublishFragment;
import cn.sinata.wanglin.utils.RxBus;
import cn.sinata.wanglin.village.activity.ActivedetailActivity;
import cn.sinata.wanglin.village.activity.ChoiceVillageActivity;
import cn.sinata.wanglin.village.activity.MakecomplaintsdetailActivity;
import cn.sinata.wanglin.village.activity.NewsinfoDetailsActivity;
import cn.sinata.wanglin.village.fragment.VillageFragment;

public class MainActivity extends BaseActivity implements EMMessageListener {
    //定义FragmentTabHost对象
    private FragmentTabHost mTabHost;
    //定义一个布局
    private LayoutInflater layoutInflater;
    //定义数组来存放Fragment界面
    @SuppressWarnings("rawtypes")
    private Class fragmentArray[] = {VillageFragment.class, NeighborFragment.class, PublishFragment.class, PropertyFragment.class, MineFragment.class};
    //定义数组来存放按钮图片
    private int mImageViewArray[] = {R.drawable.selector_tab_village, R.drawable.selector_tab_nerighbor, R.drawable.selector_tab_mine, R.drawable.selector_tab_property, R.drawable.selector_tab_mine};
    //Tab选项卡的文字
    private String mTextviewArray[] = {"小区", "邻居", "发布", "物业", "我的"};
    private ImageView iv_pub;//发布按钮
    private boolean hasLoginIM = false;
    public static final String REFRESH_WEATHER = "refresh_weather_img_now";
    // 定位相关
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;
    private int locationnumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getLocation();
        iniConfig();
        boolean fristtomain = SharedPreferencesUtils.getBoolean(Constant.SP_FRIST_TO_MAIN, true);
        if (fristtomain && "-1".equals(MyApplication.houseid)) {
            SharedPreferencesUtils.save(Constant.SP_FRIST_TO_MAIN, false);
            ActivityUtil.create(mContext).go(ChoiceVillageActivity.class)
                    .start();
        }
        boolean hasPermission = PermissionManager.request(this, Manifest.permission.READ_PHONE_STATE, "读取您的手机状态", 21);
        if (hasPermission) {
            Utils.systemErr("-----rp init------");
            RedPacket.getInstance().initContext(this.getApplicationContext());
            //打开Log开关 正式发布时请关闭
            RedPacket.getInstance().setDebugMode(true);
        }

        initView();
        getUserGroups();
        EMClient.getInstance().chatManager().addMessageListener(this);
        EMClient.getInstance().addConnectionListener(new EMConnectionListener() {
            @Override
            public void onConnected() {
            }

            @Override
            public void onDisconnected(final int error) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (error == EMError.USER_REMOVED) {
                            // 显示帐号已经被移除
                        } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {

                            if (isDestroy()) {
                                return;
                            }
                            // 显示帐号在其他设备登录
                            DialogUtils.createNoticeDialog(mContext, "请注意", "您的帐号已在其他设备登录，如非本人操作，请及时修改密码。", false
                                    , "确定", "", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            ActivityUtil.create(mContext)
                                                    .go(LoginStyleActivity.class)
                                                    .start();
                                            finish();
                                        }
                                    }, null);
                        } else {
                            if (NetUtils.hasNetwork(MainActivity.this)) {
                                //连接不到聊天服务器
                            } else {
                                //当前网络不可用，请检查网络设置
                            }
                        }
                    }
                });
            }
        });
        easeChatLogin();
        //86400000毫秒,一天；
        UpdateHelper.getInstance().autoUpdate(getAppInfo(), false, 3000);
    }

    private String getAppInfo() {
        try {
            String pkName = this.getPackageName();
            return pkName;
        } catch (Exception e) {
        }
        return "cn.sinata.wanglin";
    }

    /**
     * 接受外界URL跳转
     */
    private void iniConfig() {
        Intent from = getIntent();
        String action = from.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            Uri uri = from.getData();
            if (uri != null) {
                String data = from.getDataString();
                Utils.systemErr("--getDataString--" + data);
                String type = uri.getQueryParameter("type");
                Utils.systemErr("--type--" + type);
                if (TextUtils.isEmpty(type)) {
                    return;
                }
                String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
                if (TextUtils.isEmpty(userid)) {
                    showToast("请登录！");
                    ActivityUtil.create(mContext).go(LoginStyleActivity.class)
                            .start();
                    finish();
                    return;
                }
                try {
                    performAction(Integer.parseInt(type), uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 相应不同的action
     *
     * @param type
     * @param uri
     */
    private void performAction(int type, Uri uri) {
        String id = uri.getQueryParameter("id");
        switch (type) {
            case 1:
                //跳转到吐槽详情
                ActivityUtil.create(mContext).go(MakecomplaintsdetailActivity.class)
                        .put("type", "1")
                        .put("id", id)
                        .start();
                break;
            case 2:
                //跳转到八卦详情
                ActivityUtil.create(mContext).go(MakecomplaintsdetailActivity.class)
                        .put("type", "2")
                        .put("id", id)
                        .start();
                break;
            case 3:
                //跳转到活动详情
                ActivityUtil.create(mContext).go(ActivedetailActivity.class)
                        .put("id", id)
                        .start();
                break;
            case 4:
                //跳转到新闻详情
                ActivityUtil.create(mContext).go(NewsinfoDetailsActivity.class)
                        .put("id", id)
                        .start();
                break;
        }
    }

    private void getWeather() {
        HttpManager.getWeatherByCityName().subscribe(new ResultSubscriber<WeatherInfo>(this) {
            @Override
            public void onCompleted() {
                super.onCompleted();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(WeatherInfo weatherInfo) {
                super.onNext(weatherInfo);
                RxBus.get().post(REFRESH_WEATHER, weatherInfo);
            }
        });
    }

    /**
     * 初始化组件
     */
    private void initView() {
        //实例化布局对象
        layoutInflater = LayoutInflater.from(this);
        iv_pub = (ImageView) findViewById(R.id.iv_pub);
        iv_pub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(MyApplication.houseid) || "-1".equals(MyApplication.houseid)) {
                    showToast("请先选择小区！");
                    ActivityUtil.create(mContext).go(ChoiceVillageActivity.class)
                            .start();
                    return;
                }
                ActivityUtil.create(mContext).go(PubhomeActivity.class)
                        .startForResult(3);
            }
        });
        //实例化TabHost对象，得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        //得到fragment的个数
        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
        }
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null, false);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);
        if (index == 2) {
            textView.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
        } else {
            textView.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.VISIBLE);
        }
        return view;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length <= 0) {
            return;
        }
        SharedPreferencesUtils.save(permissions[0], false);
        if (requestCode == 21 && permissions[0].equals(Manifest.permission.READ_PHONE_STATE)) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                RedPacket.getInstance().initContext(this.getApplicationContext());
                if (hasLoginIM) {
                    final String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
                    initRedPacketToken(account);
                }
            }
        }
    }

    /**
     * 监听返回--是否退出程序
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void easeChatLogin() {
        if (EMClient.getInstance().isConnected()) {
            EMClient.getInstance().logout(true);
        }

        final String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
        String pwd = SharedPreferencesUtils.getString(Constant.SP_IM_PWD);
        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(pwd)) {
            showToast("无法登录聊天服务器，请重新登录重试！");
            return;
        }
        EMClient.getInstance().login(account, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                hasLoginIM = true;
                String name = SharedPreferencesUtils.getString(Constant.SP_NICKNAME);
                EMClient.getInstance().updateCurrentUserNick(name);
                boolean hasPermission = PermissionManager.request((Activity) mContext, Manifest.permission.READ_PHONE_STATE, "读取您的手机状态", 21);
                if (hasPermission) {
                    RedPacket.getInstance().initContext(mContext.getApplicationContext());
                    initRedPacketToken(account);
                }
//                EMClient.getInstance().groupManager().loadAllGroups();
            }

            @Override
            public void onError(int i, String s) {
                Utils.systemErr("onError--" + s);
            }

            @Override
            public void onProgress(int i, String s) {
                Utils.systemErr("onProgress--" + s);
            }
        });
    }

    void initRedPacketToken(String account) {

//        RedPacket.getInstance().initRPToken(tok);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(this);
    }

    void refreshTabUnRead() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    TextView tipView = (TextView) mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.tipView);
                    int count = EMClient.getInstance().chatManager().getUnreadMsgsCount();
                    if (count > 0) {
                        tipView.setVisibility(View.VISIBLE);
                        if (count > 99) {
                            tipView.setText("99");
                        } else {
                            tipView.setText(count + "");
                        }
                    } else {
                        tipView.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshTabUnRead();
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {
        Utils.systemErr(list);
        for (EMMessage emMessage : list) {
            if (emMessage.getChatType() == EMMessage.ChatType.GroupChat) {
                String fromUser = emMessage.getFrom();//群消息发送人
                String toUser = emMessage.getTo();//群ID
                String nick = emMessage.getStringAttribute("nick", "");
                String headUrl = emMessage.getStringAttribute("headUrl", "");
                String groupId = emMessage.getStringAttribute("groupId", "");
                String groupName = emMessage.getStringAttribute("groupName", "");
                String groupImg = emMessage.getStringAttribute("groupImg", "");
                Utils.systemErr(emMessage.ext());
                //关联用户群昵称到本地表。
                GroupUserDao.getInstance(this).saveGroupUser(toUser, fromUser, nick, headUrl);
                String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
                Group group = new Group();
                group.setGroupImg(groupImg);
                group.setId(groupId);
                group.setGroupName(groupName);
                //存储群信息用于消息面打扰
                GroupDao.getInstance(this).saveGroup(userId, group);
                //存储群头像，名称，用于聊天列表展示
                UserDao.getInstance(this).saveUser(toUser, groupName, groupImg);
            } else if (emMessage.getChatType() == EMMessage.ChatType.Chat) {
                String fromUser = emMessage.getFrom();
                String nick = emMessage.getStringAttribute("nick", "");
                String headUrl = emMessage.getStringAttribute("headUrl", "");
                UserDao.getInstance(this).saveUser(fromUser, nick, headUrl);
            }
            EaseUI.getInstance().getNotifier().vibrateAndPlayTone(emMessage);
        }
        refreshTabUnRead();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
        for (EMMessage emMessage : list) {
            Utils.systemErr(emMessage);
            if (emMessage.getType() == EMMessage.Type.CMD) {
                String toUser = emMessage.getTo();

                EMCmdMessageBody messageBody = (EMCmdMessageBody) emMessage.getBody();
                String action = messageBody.action();
                if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(emMessage);
                } else {
                    Map<String, String> ext = messageBody.getParams();
                    if (ext == null) {
                        ext = new HashMap<>();
                    }

                    String time = null;
                    //如果是圈子新消息
                    if (action.equals(Constant.Push.CMD_MEG_TYPE_C)) {
                        ext.put("sys_time", emMessage.getStringAttribute("sys_time", "0"));
                        ext.put("headUrl", emMessage.getStringAttribute("headUrl", ""));
                        time = ext.get("sys_time");
                    }
                    JSONObject jsonObject = new JSONObject(ext);
                    PushDao.getInstance(this).savePushData(toUser, action, jsonObject.toString(), time);
                    if (action.equals(Constant.Push.CMD_MEG_TYPE_FK) || action.equals(Constant.Push.CMD_MEG_TYPE_G)
                            || action.equals(Constant.Push.CMD_MEG_TYPE_F) || action.equals(Constant.Push.CMD_MEG_TYPE_GA)) {
                        EaseUI.getInstance().getNotifier().vibrateAndPlayTone(emMessage);
                    }
                    if (action.equals(Constant.Push.CMD_MEG_TYPE_T)) {
                        Intent intent = new Intent();
                        intent.setAction(Constant.BROADCAST_MSG_ME);
                        sendBroadcast(intent);
                    }
                }
            }
        }
        String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
        int count = PushDao.getInstance(this).getUnReadNum(account, Constant.Push.CMD_MEG_TYPE_C);
        MyApplication.circleUnRead += count;
    }

    @Override
    public void onMessageReadAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageDeliveryAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case 1://第一次选择小区结果还回
                        break;
                }
                break;
            case 3://发布吐槽回传
                if (requestCode == 3) {
                    mTabHost.setCurrentTab(0);
                    String tag = mTabHost.getCurrentTabTag();
                    VillageFragment mVillageFragment = (VillageFragment) getSupportFragmentManager().findFragmentByTag(tag);
                    mVillageFragment.reRefresh(1);
                }
                break;
            case 4://发布同城八卦回传
                if (requestCode == 3) {
                    mTabHost.setCurrentTab(0);
                    String tag = mTabHost.getCurrentTabTag();
                    VillageFragment mVillageFragment = (VillageFragment) getSupportFragmentManager().findFragmentByTag(tag);
                    mVillageFragment.reRefresh(2);
                }
                break;
            case 5://发布活动回传
                if (requestCode == 3) {
                    mTabHost.setCurrentTab(0);
                    String tag = mTabHost.getCurrentTabTag();
                    VillageFragment mVillageFragment = (VillageFragment) getSupportFragmentManager().findFragmentByTag(tag);
                    mVillageFragment.reRefresh(4);
                }
                break;
        }
    }

    void getUserGroups() {
        final String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        final String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
        final String headUrl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
        if (!TextUtils.isEmpty(userId)) {
            HttpManager.userGroups(userId)
                    .subscribe(new ResultDataSubscriber<ArrayList<Group>>(this) {
                        @Override
                        public void onSuccess(String msg, ArrayList<Group> groups) {
                            if (groups == null || groups.size() == 0) {
                                return;
                            }
                            for (Group group : groups) {
                                GroupDao.getInstance(mContext).saveGroup(userId, group);
                                GroupUserDao.getInstance(mContext).saveGroupUser(group.getGroupAccount(), account, group.getGroupNickName(), headUrl);
                            }
                        }

                        @Override
                        protected boolean shouldShowErrorToast() {
                            return false;
                        }
                    });
        }
    }

    public int getCurrentTab() {
        if (mTabHost == null) {
            return 0;
        }
        return mTabHost.getCurrentTab();
    }

    @Override
    protected boolean finishWhenCancelDialog() {
        return false;
    }


    private void getLocation() {
        // 设置相关参数
        LocationClientOption option = new LocationClientOption();
        // 打开gprs
        option.setOpenGps(true);
        option.setLocationNotify(true);
        // 设置坐标类型
        option.setCoorType("bd09ll");
        // 设置扫描速度
        option.setScanSpan(3000);
        option.setIsNeedAddress(true);
        option.setLocationMode(com.baidu.location.LocationClientOption.LocationMode.Battery_Saving);
        mLocationClient = new LocationClient(this.getApplicationContext(), option);
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        mLocationClient.start();
    }

    /**
     * 实现实位回调监听
     */

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            if (TextUtils.isEmpty(location.getNetworkLocationType())) {
                if (locationnumber > 15) {
                    mLocationClient.stop();
                    locationnumber = 0;
                    return;
                }
                locationnumber++;
                return;
            }
            if (TextUtils.isEmpty("" + location.getLatitude()) || TextUtils.isEmpty("" + location.getLongitude())) {
                return;
            }
            mLocationClient.stop();
            MyApplication.lat = location.getLatitude();
            MyApplication.lng = location.getLongitude();
            MyApplication.city = location.getCity();
            MyApplication.cityCode = location.getCityCode();

            getWeather();

        }
    }

}
